import { Module } from '@nestjs/common';
import { UploadController } from './upload.controller';
import { MulterModule } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { ServeStaticModule } from '@nestjs/serve-static';
import * as path from 'path';
import { UploadService } from './upload.service';
import * as fs from 'fs';

const uploadsDir = path.resolve(__dirname, '../public/uploads');

if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { recursive: true });
}

@Module({
  imports: [
    MulterModule.register({
      storage: diskStorage({
        //文件上传的地址
        destination: uploadsDir,
        filename: (_, file, callback) => {
          const fileName = `${
            new Date().getTime() + path.extname(file.originalname)
          }`;
          callback(null, fileName);
        },
      }),
    }),
    ServeStaticModule.forRoot({
      //静态文件目录
      rootPath: uploadsDir,
      serveRoot: '/static',
      serveStaticOptions: {
        // 禁用缓存控制，确保每次请求都能正确处理CORS
        cacheControl: false,
        // 添加CORS头信息
        setHeaders: (res) => {
          // 为所有静态资源添加CORS头
          res.setHeader('Access-Control-Allow-Origin', '*');
          res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
          res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'); // 允许资源跨域访问
        },
      },
    }),
  ],
  controllers: [UploadController],
  providers: [UploadService],
})
export class UploadModule {}
